<template>
  <div>
    <div class="top-select" style="display: flex;">
      <el-select v-model="value1" placeholder="学期">
        <el-option v-for="item in semester" :key="item" :label="item" :value="item"></el-option>
      </el-select>
      <el-select v-model="value2" placeholder="年级" @change="queryClass">
        <el-option v-for="item in grade" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <el-select v-model="value3" placeholder="班级" @change="queryCoursePlan">
        <el-option v-for="item in classNo" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>

      <!-- 新增按钮 -->
      <el-button type="primary" @click="showAddCoursePlanDialog">新增课程计划</el-button>
    </div>


    <div>
      <el-table :data="tableData" style="width: 100%" :row-style="{ height: '85px' }">
        <el-table-column
            v-for="(header, index) in headers"
            :key="index"
            :label="header"
            align="center">
          <template #default="scope">
            <div v-if="dataMap[`${index}${scope.$index}`]" @click="handleClick(index, scope.$index)">
              <p>{{ dataMap[`${index}${scope.$index}`].realname }}</p>
              <p>{{ dataMap[`${index}${scope.$index}`].courseName }}</p>
              <p>{{ dataMap[`${index}${scope.$index}`].classroomNo }}</p>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog v-model="dialogVisible" title="编辑课程信息">
        <el-form :model="dialogData">
          <el-form-item label="可选上课时间">
            <el-select v-model="classtimeValue" placeholder="上课时间" @change="queryUseClassroom">
              <el-option v-for="item in classtimes" :key="item.index" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="教师">
            <el-input disabled v-model="dialogData.realname"></el-input>
          </el-form-item>
          <el-form-item label="课程">
            <el-input disabled v-model="dialogData.courseName"></el-input>
          </el-form-item>

          <el-form-item label="空闲教室">
            <el-select v-model="classroomValue" placeholder="空闲教室">
              <el-option v-for="item in classrooms" :key="item.index" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveData">保存</el-button>
          <el-button type="danger" @click="deleteData">删除</el-button>
        </div>
      </el-dialog>


      <el-dialog v-model="dialogVisible2" title="新增课程信息">
        <el-form :model="dialogData2">
          <el-form-item label="课程">
            <el-select v-model="dialogData2.courseNo" placeholder="课程">
              <el-option v-for="item in courseinfos" :key="item.index" :label="item.courseName"
                         :value="item.courseNo"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="上课时间">
            <el-select v-model="dialogData2.classTime" placeholder="上课时间" @change="queryUseClassTime2">
              <el-option v-for="item in classtimes2" :key="item.index" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="教师">
            <el-select v-model="dialogData2.teacherNo" placeholder="教师">
              <el-option v-for="item in teachers2" :key="item.index" :label="item.realname"
                         :value="item.teacherNo"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="教室">
            <el-select v-model="dialogData2.classroomNo" placeholder="教室">
              <el-option v-for="item in classrooms2" :key="item.index" :label="item.classroomNo"
                         :value="item.classroomNo"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="saveData2">保存</el-button>
        </div>
      </el-dialog>
    </div>

  </div>
</template>

<script setup>
import {ref, onMounted, getCurrentInstance} from 'vue';
import {useRouter} from 'vue-router';
import {useStore} from 'vuex';

//于获取当前组件实例的 API
const {proxy} = getCurrentInstance();
const store = useStore();
const router = useRouter();

const semester = ref([]);
const grade = ref([
  {value: "01", label: "高一"},
  {value: "02", label: "高二"},
  {value: "03", label: "高三"},
]);
const classNo = ref([]);
const value1 = ref("");
const value2 = ref("");
const value3 = ref("");
const getSemester = async () => {
  const result = await proxy.$api.getSemester();
  semester.value = result;
};
onMounted(() => {
  // 假设在组件挂载时初始化班级编号和名称
  classNo.value = [
    {value: "", label: ""},
  ];
  getSemester()
});


//  客户端进行查询班级编号和名称
const queryClass = async () => {
  const result = await proxy.$api.queryClass(value2.value);
  classNo.value.splice(0, classNo.value.length)
  result.map((v) => {
    classNo.value.push({
      value: v.classNo,
      label: v.className,
    });
  })
}

// 查询课程表
const queryCoursePlan = async () => {
  const courseData = await proxy.$api.queryCourseplan(value3.value);

  dataMap.value = {}
  backendData.value = courseData;
  getCourseData();
}

const headers = ['周一', '周二', '周三', '周四', '周五'];
const tableData = Array.from({length: 8}).map((_, i) => ({}));

const backendData = ref([]);

const dataMap = ref({});


const getCourseData = () => {
  backendData.value.forEach(item => {
    const row = Math.floor((item.classTime - 1) / 8);
    const col = (item.classTime - 1) % 8;
    dataMap.value[`${row}${col}`] = item;
  });

// console.log(dataMap.value);
}

const dialogVisible = ref(false);
const dialogData = ref({});

// 可选时间
const classtimes = ref([]);
// 选择的时间
const classtimeValue = ref("");

// 可选教室
const classrooms = ref([]);
// 选择的教室
const classroomValue = ref("");


const handleClick = async (row, col) => {
  const key = `${row}${col}`;
  dialogData.value = {...dataMap.value[key]};  // 使用解构以创建一个新对象，防止直接修改dataMap中的值

  // 可选时间段的获取
  const id = dataMap.value[key].id;
  classtimes.value = await proxy.$api.unUseClassTime(id);
  classtimeValue.value = dataMap.value[key].classTime;

  classroomValue.value = dataMap.value[key].classroomNo;

  queryUseClassroom();

  dialogVisible.value = true;
};


const queryUseClassroom = async () => {
  const result = await proxy.$api.unUseClassroom({
    id: dialogData.value.id,
    classTime: classtimeValue.value,
  })
  classrooms.value = result;

  if (classrooms.value.length === 0) {
    proxy.$message.error("该时间段没有空闲教室");
  }
}


const saveData = async () => {
  // 在此处添加保存数据的逻辑，例如发送请求到后端
  console.log('Saving data', dialogData.value);

  const result = await proxy.$api.updateCoursePlan({
    id: dialogData.value.id,
    classroomNo: classroomValue.value,
    classTime: classtimeValue.value,
  })

  dialogVisible.value = false;

  // 清空数据
  dialogData.value = {}
  dataMap.value = {};
  queryCoursePlan();
};

const deleteData = async () => {
  // 在此处添加删除数据的逻辑，例如发送请求到后端
  const res = await proxy.$api.deleteCoursePlanById(dialogData.value.id);
  dialogVisible.value = false;
  dialogData.value.id = "";

  dataMap.value = {};
  queryCoursePlan();
};


// 新增课程计划逻辑
const dialogVisible2 = ref(false);
const dialogData2 = ref({
  semester: value1.value,
  gradeNo: value2.value,
  classNo: value3.value,

  courseNo: "",
  teacherNo: "",
  classroomNo: "",
  classTime: "",
});

// 该班级可用上课时间
const classtimes2 = ref([]);

// 所有课程信息
const courseinfos = ref([]);

// 可选教师列表
const teachers2 = ref([]);

// 可选教室列表
const classrooms2 = ref([]);

const showAddCoursePlanDialog = async () => {
  if (value3.value == null || value3.value == "") {
    ElMessage('请选择班级~');
    return
  }

  dialogData2.value = {
    semester: value1.value,
    gradeNo: value2.value,
    classNo: value3.value,

    courseNo: "",
    teacherNo: "",
    classroomNo: "",
    classTime: "",
  }

  await proxy.$api.unUseClassTimeByClassNo(value3.value,
  ).then(res => {
    classtimes2.value = res;
  })

  courseinfos.value = await proxy.$api.allCourseInfoAll();

  dialogVisible2.value = true;
};


const queryUseClassTime2 = async () => {
  if (dialogData2.value.classTime == null || dialogData2.value.classTime == "") {
    ElMessage('请选择时间段~');
    return
  }

  await proxy.$api.unUseTeacherByClassTime(dialogData2.value.classTime,
  ).then(res => {
    teachers2.value = res;
  })

  if (dialogData2.value.classNo == "" || dialogData2.value.classNo == null) {
    ElMessage('请先选择课程~');
    return
  }

  await proxy.$api.unUseClassroomByClassTimeAndCourseAttr({
    courseNo: dialogData2.value.courseNo,
    classTime: dialogData2.value.classTime,
  }).then(res => {
    classrooms2.value = res;
  })
}

const saveData2 = async () => {
  const isValid =
      dialogData2.value.semester && dialogData2.value.semester !== '' &&
      dialogData2.value.gradeNo && dialogData2.value.gradeNo !== '' &&
      dialogData2.value.classNo && dialogData2.value.classNo !== '' &&
      dialogData2.value.courseNo && dialogData2.value.courseNo !== '' &&
      dialogData2.value.teacherNo && dialogData2.value.teacherNo !== '' &&
      dialogData2.value.classroomNo && dialogData2.value.classroomNo !== '' &&
      dialogData2.value.classTime && dialogData2.value.classTime !== '';

  if (!isValid) {
    ElMessage('请填写完整~');
    return
  }

  console.log("=================================");
  console.log(dialogData2.value);
  const b = await proxy.$api.addCoursePlan(dialogData2.value)
  if (b) {
    ElMessage('添加成功~');
  } else {
    ElMessage('添加失败');
  }

  dialogData2.value = {
    semester: value1.value,
    gradeNo: value2.value,
    classNo: value3.value,

    courseNo: "",
    teacherNo: "",
    classroomNo: "",
    classTime: "",
  }
  dialogVisible2.value = false;

  queryCoursePlan();
}


</script>

<style scoped>
.el-table th {
  text-align: center;
}

.el-table td {
  cursor: pointer;
}
</style>